import React from 'react'
import {Radio,List,DatePickerView,Tools,Button} from 'weaver-mobile'
import { withRouter } from 'react-router-dom';
import { observer, inject} from 'mobx-react';

const RadioItem = Radio.RadioItem;
const getLabel = Tools.getLabel;

@inject('createStore')
@observer
@withRouter
export default class EndRepeat extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '0',
      time: null,
      datestr: this.props.repeatOptions[0].showname,
    }
  }

  componentDidMount() {
    const {endrepeatDate} = this.props.createStore;
    if(endrepeatDate.split('-').length > 1){
      this.setState({value: '1',time: new Date(endrepeatDate)})
    }else{
      this.setState({value: '0'})
    }
  }

  onChangeRadio = (value) => {
    const {form} = this.props.createStore;
    form.updateField('moudulEndDate',value);

    value === '1' && this.setState({value: value,time: new Date()})
    value === '0' && this.setState({value: value,})
  }

  getRadio = () => {
    const options = this.props.repeatOptions;
    const { value } = this.state;
    let radios = [];
    options && options.map(item => (
      radios.push(
        <RadioItem key={item.key} checked={value === item.key} onChange={() => {this.onChangeRadio(item.key)}}>
          {item.showname}      
        </RadioItem>
      )
    ))

    return radios;
  }

  onChange = (value) => {
    this.setState({time: value})
  }
 
  setNum = (num) => {
    if(num > 9){
      return num;
    }else{
      return '0'+num;
    }
  }
 
  submit = () => {
    const {setParams,setRepeatInfo} = this.props.createStore;
    const {value,time,datestr} = this.state;
    if(value === '1') {
      let datestring = time.getFullYear() + '-' + this.setNum(time.getMonth()+1) + '-' + this.setNum(time.getDate());
      setRepeatInfo({availableEndDate: datestring})
      setParams({endrepeatDate: datestring})
    }
    if(value === '0') {
      setRepeatInfo({availableEndDate: datestr})
      setParams({endrepeatDate: datestr})
    }
    this.props.history.go(-1);
  }

  parserDate = (date: string | Date) => {
    if (typeof date !== 'string') { return date; }
    date = date.replace(/-/g, '/');
    const t = Date.parse(date);
    if (!isNaN(t)) {
      return new Date(t);
    } else {
      return new Date();
    }
  }

  render() {
    const {form} = this.props.createStore;
    const datastr = form.formParams['beginDateTime'];
    return (
      <div className="endRepeat">
        <List>
        {this.getRadio()}
        {this.state.value === '1' && <DatePickerView
          mode='date'
          minDate={this.parserDate(datastr)}
          value={this.state.time}
          onChange={this.onChange}
        />}
     
        </List>
        <div className='endRepeat-button'>
          <Button type="primary" onClick={() => {this.submit()}}>{getLabel(386788,'确定')}</Button>
        </div>
      </div>
    );
  }
}